package de.caeci.iserv;

import java.net.HttpURLConnection;
import java.util.Enumeration;
import java.util.Hashtable;

public class Cookie {
	private Hashtable<String, String> values;
	public Cookie(HttpURLConnection connection) {
		values = new Hashtable<String, String>();
		init(connection);
	}
	
	private void setCookieValue(String cookieStringFromHttpHeader) {
		String[] cookieParts = cookieStringFromHttpHeader.split(";");
		String[] keyVal = cookieParts[0].split("=");
		values.put(keyVal[0], keyVal[1]);
	}
	
	public String toString() {
		StringBuffer result = new StringBuffer();
		Enumeration<String> keys = values.keys();
		while (keys.hasMoreElements()) {
			String key = keys.nextElement();
			result.append(key).append("=").append(values.get(key));
			if (keys.hasMoreElements()) {
				result.append(";");
			}
		}
		return result.toString();
	}

	private void init(HttpURLConnection connection) {
		String headerName = null;
		for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
			if (headerName.equalsIgnoreCase("SET-COOKIE")) {
				String cookieValue = connection.getHeaderField(i);
				setCookieValue(cookieValue);
			}
		}
	}
}
